import {useRunInfoStore} from "../store/runInfo"
import {useGroupStore} from "../store/group"
const request = (url, method = 'GET', data = {}) => {
  let token = uni.getStorageSync('token');
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			data: data,
			method: method,
			header: {
				'X-Requested-With': 'XMLHttpRequest',
				"Accept": "application/json",
				"Content-Type": 'application/json',
        "Authorization":`Bearer ${token}`
			},
			dataType: 'json',
			success: (res) => {
        if (res.statusCode === 200) {
          const responseData = interceptor(res.data);
          if (responseData.code === 0) {
            resolve(responseData);
          } else {
            if (responseData.code != 40003) {
              throwErr(responseData)
            }
            reject(res);
          }
        }
        if (res.statusCode === 403) {
          uni.clearStorageSync()
          uni.reLaunch({
					  url: '/pages/chat/chat',
				  });
          const useRunInfoData = useRunInfoStore()
          const useGroupData = useGroupStore()
          useRunInfoData.stopCountDown()
          useRunInfoData.resetAll()
          useGroupData.resetAll()
        }
			},
			fail: function(err) {
				reject(err)
			}
		})
	});
};
 
// GET 请求封装
const get = (url, data) => {
	return request(url, data, 'GET');
};
 
// POST 请求封装
const post = (url, data) => {
	return request(url, data, 'POST');
};
// PUT 请求封装
const put = (url, data) => {
	return request(url, data, 'PUT');
};
 
// DELETE 请求封装
const del = (url, data) => {
	return request(url, data, 'DELETE');
};
 
// 请求拦截
function interceptor(response) {
	if (response.code === 40003) {
		// uni.showToast({
		// 	title: response.msg,
		// 	icon: 'none',
		// 	duration: 2000,
		// 	complete: () => {
		// 		// uni.reLaunch({
		// 		// 	url: '/pages/chat/chat',
		// 		// });
		// 	},
		// });
		// return false;
	}
	return response;
}
 
// 处理错误
function throwErr(res) {
  uni.showToast({
    title: res.message,
    icon: "none"
  })
}
 
export {
	get,
	post,
	put,
	del,
  request
}